
#include <iostream>

#include "InputManager.h"
#include "SB.h"

InputManager::InputManager()
{
    updateInputs();
    m_eMotionDirection = MOTION_NONE;
}

InputManager::~InputManager()
{
}

void InputManager::updateInputs()
{
    m_eMotionDirection = MOTION_NONE;
    
    m_fTimeSinceLastJustPressed += SB::dt;
    
    // update the latest positions vector if the player moves the cursor
    if (m_bJustMoved)
    {
        for(int i=MAX_LATEST_POSITIONS - 1; i > 0; --i)
        {
            m_avLatestPositions[i] = m_avLatestPositions[i - 1];
        }
        m_avLatestPositions[0].x = m_vPosition.x;
        m_avLatestPositions[0].y = m_vPosition.y;
        m_avLatestPositions[0].z = SB::gameTime;
        if (m_avLatestPositions[MAX_LATEST_POSITIONS-1].z != 0.0f)
        {
            Vector3 vSpeed = m_avLatestPositions[0] - m_avLatestPositions[MAX_LATEST_POSITIONS - 1];
            // to avoid having infinite values on m_vSpeed
            if (vSpeed.z < 0.01f) vSpeed.z = 0.01;
            m_vSpeed = Vector2(vSpeed.x, vSpeed.y) / vSpeed.z;  
        }
        else
        {
            m_vSpeed = Vector2(0.0f, 0.0f);
        }
    }
    else // or reset it
    {
        for(int i=0; i<MAX_LATEST_POSITIONS; ++i)
        {
            m_avLatestPositions[i] = Vector3(0.0f, 0.0f, 0.0f);
        }
        m_vSpeed = Vector2(0.0f, 0.0f);
    }
    
    // reset variables
    m_bJustPressed = false;
    m_bJustMoved = false;
    m_bJustReleased = false;
}

bool InputManager::hasJustPressed() 
{ 
    return m_bJustPressed; 
}

bool InputManager::hasJustMoved() 
{ 
    return m_bJustMoved; 
}

bool InputManager::hasJustReleased() 
{ 
    return m_bJustReleased; 
}

bool InputManager::isPressed() 
{ 
    return m_bPressed; 
}

Vector2 InputManager::getPosition() 
{ 
    return m_vPosition; 
}

Vector2 InputManager::getSpeed() 
{ 
    return m_vSpeed; 
}

void InputManager::setJustPressed(Vector2 _vPosition) 
{ 
    m_bJustPressed = true; 
    m_vPosition = _vPosition; 
    m_bPressed = true; 
    
    m_fTimeSinceLastJustPressed = 0.0f;
    m_vLastJustPressedPos = _vPosition;
}

Vector2 InputManager::getLastJustPressedPosition()
{
    return m_vLastJustPressedPos;
}
float InputManager::getTimeSinceLastJustPressed()
{
    return m_fTimeSinceLastJustPressed;
}

void InputManager::setJustMoved(Vector2 _vPosition) 
{ 
    m_bJustMoved = true; 
    m_vPosition = _vPosition; 
}

void InputManager::setJustReleased(Vector2 _vPosition) 
{ 
    m_bJustReleased = true; 
    m_vPosition = _vPosition; 
    m_bPressed = false; 
}

bool InputManager::positionInRect(Vector2 _vPos, Vector2 _vSize)
{
    Vector2 vPos = m_vPosition * SB::contentScale;
    return vPos.x >= _vPos.x && vPos.y >= _vPos.y && vPos.x <= _vPos.x + _vSize.x && vPos.y <= _vPos.y + _vSize.y;
}
